const fs = require('fs');
const path = require('path');
const chokidar = require('chokidar');
// const minimatch = require("minimatch");

// console.log(minimatch("src/test.js", "**/test.js")); // 测试 minimatch 功能

// 配置参数
const config = {
  // targetDir: 'files',    // 要监控的目录
  targetDir: 'C:/Users/lijinbei/Desktop/files',    // 要监控的目录
  jsonFile: 'now.json', // JSON格式目录结构文件
  ignorePatterns: [
  ] // 忽略模式
};


// 生成目录结构对象
function generateDirectoryStructure(dir) {
  const name = path.basename(dir);
  const stats = fs.statSync(dir);
  const item = {
    name: name,
    path: dir,
    type: 'directory',
    "mtime": stats.mtimeMs.toString(),
    children: []
  };

  const items = fs.readdirSync(dir);
  
  items.forEach(childName => {
    // if (config.ignorePatterns.some(pattern => 
    //   minimatch(path.join(dir, childName), pattern)
    // )) return;

    const fullPath = path.join(dir, childName);
    const stats = fs.statSync(fullPath);
    
    if (stats.isDirectory()) {
      item.children.push(generateDirectoryStructure(fullPath));
    } else {
      item.children.push({
        name: childName,
        path: fullPath,
        type: 'file',
        mtime: stats.mtimeMs.toString()
      }); 
    }
  });

  return item;
}

// 更新目录结构JSON文件
function updateStructureJson() {
  const timestamp = new Date().toISOString();
  // const structure = {
  //   timestamp: timestamp,
  //   monitoredPath: config.targetDir,
  //   structure: generateDirectoryStructure(config.targetDir)
  // };

  const structure = generateDirectoryStructure(config.targetDir);

  fs.writeFileSync(
    config.jsonFile, 
    JSON.stringify(structure, null, 2), // 美化输出，缩进2空格
    'utf8'
  );
  console.log(`目录结构已更新: ${timestamp}`);
}

// 初始化JSON文件
if (!fs.existsSync(config.jsonFile)) {
  updateStructureJson();
} else {
  console.log(`使用现有JSON文件: ${config.jsonFile}`);
}

// 创建监控实例
const watcher = chokidar.watch(config.targetDir, {
  ignored: config.ignorePatterns,
  persistent: true,
  ignoreInitial: true,
  awaitWriteFinish: {
    stabilityThreshold: 1000,
    pollInterval: 100
  }
});

// 事件监听 - 精简为只监听影响目录结构的事件
const debouncedUpdate = debounce(updateStructureJson, 500);
watcher
  .on('add', path => {
    console.log(`文件添加: ${path}`);
    debouncedUpdate();
  })
  .on('addDir', path => {
    console.log(`目录添加: ${path}`);
    debouncedUpdate();
  })
  .on('unlink', path => {
    console.log(`文件删除: ${path}`);
    debouncedUpdate();
  })
  .on('unlinkDir', path => {
    console.log(`目录删除: ${path}`);
    debouncedUpdate();
  })
  .on('error', error => console.error('监控错误:', error));

console.log(`开始监控目录: ${config.targetDir}`);
console.log(`目录结构将保存到: ${path.resolve(config.jsonFile)}`);

// 防抖函数避免频繁更新
function debounce(func, wait) {
  let timeout;
  return function() {
    clearTimeout(timeout);
    timeout = setTimeout(() => func.apply(this, arguments), wait);
  };
}

// 优雅退出
process.on('SIGINT', () => {
  watcher.close().then(() => {
    console.log('监控已停止');
    process.exit();
  });
});